﻿using DevelopTool.Bll.ChatBlls;
using DevelopTool.Bll.DesktopClockBlls;
using DevelopTool.Bll.LocalDbBlls;
using DevelopTool.Bll.PowerPlanBlls;
using DevelopTool.Bll.SchedulerBlls;
using DevelopTool.Bll.TipsBlls;
using DevelopTool.Bll.WiFiFixatorBlls;
using DevelopTool.Common;
using DevelopTool.Forms;
using DevelopTool.Forms.BaseForms;
using DevelopTool.Forms.CommonForms;
using DevelopTool.Forms.CommonHelpers;
using DevelopTool.Forms.FolderToolForms;
using DevelopTool.Forms.ImageToolForms;
using DevelopTool.Forms.SafetyForms;
using DevelopTool.Forms.TextProcessForms;
using DevelopTool.Forms.ToolForms;
using DevelopTool.Model;
using DevelopTool.Model.ChatModels;
using DevelopTool.Model.CommonModels;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DevelopTool
{
    /// <summary>
    /// 主窗口（框架）
    /// </summary>
    public partial class MainForm : BaseUIForm
    {
        /// <summary>
        /// 是否已最小化到托盘
        /// </summary>
        private bool hidenTheTaskBar = false;

        /// <summary>
        /// 当前的锁定状态，true=已锁定，false=未锁定
        /// </summary>
        private bool lockState = false;

        /// <summary>
        /// 锁屏窗口对象
        /// </summary>
        private LockForm lockForm = null;


        /// <summary>
        /// 启动方式是否是系统自动启动
        /// </summary>
        private bool fromToAutoStart = false;

        /// <summary>
        /// 启动参数
        /// </summary>
        private string[] args;

        public MainForm(bool fromToAutoStart, string[] args)
        {
            InitializeComponent();

            this.fromToAutoStart = fromToAutoStart;
            this.args = args;
        }


        private void MainForm_Load(object sender, EventArgs e)
        {
            SystemEx.SetProcessDPIAware();//通知系统本程序已自行适配高DPI，不需要再进行缩放

            GlobalData.MainForm = this;//将本主窗体实例共享出去，以便其它功能调用                               

            Text += " V" + Application.ProductVersion.ToString();//设置标题

            #region 延迟运行一些东西
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer
            {
                Interval = 500,
                Enabled = true//启动计时器
            };
            timer.Tick += delegate (object ss, EventArgs ee)
            {
                timer.Stop();//停止计时器

                LoadMenus();//加载顶部菜单

                #region 启动不需要登录就能运行的Quartz任务
                new WiFiFixatorBll().StartJob();//启动WiFi监控定时任务
                new PowerPlanBll().StartJob();//启动电源计划监控任务
                new DesktopClockBll().Start();//启动桌面时钟
                #endregion 启动不需要登录就能运行的Quartz任务

                #region 注册全局快捷键（热键）
                this.RegisterGlobalHotKey(Setting.ScreenShot.HotKey);//截图快捷键
                this.RegisterGlobalHotKey(Setting.AuxiliaryInput.StartHotKey);//辅助输入快捷键
                #endregion

                #region 设置扩展按钮

                选项ToolStripMenuItem.Image = FontImageHelper.CreateImage(61459, 24, Color.Black);
                主题ToolStripMenuItem.Image = FontImageHelper.CreateImage(61668, 24, Color.Black);
                本地数据库ToolStripMenuItem.Image = FontImageHelper.CreateImage(557705, 24, Color.Black);
                配置文件ToolStripMenuItem.Image = FontImageHelper.CreateImage(362836, 24, Color.Black);
                打开临时目录ToolStripMenuItem.Image = FontImageHelper.CreateImage(57476, 24, Color.Black);
                SetBtnHelpProperty();

                #endregion 设置扩展按钮


                _ = Task.Factory.StartNew(() =>
                {
                    ListenWindowBringToFront();
                });//后台线程监听命名管道消息，还原窗口到前台显示

                LogingWait(false);//等待登录

                #region 自启动后是否需要缩小到系统托盘
                if (fromToAutoStart)
                {
                    if (Setting.System.SendMsgModule.Contains("AutoStartLog"))
                        FeiShuMsgHelper.SendCardMsgAsync($"{GlobalData.AppName_zh}自启动");

                    if (Setting.System.AutoStartWindowMini)
                    {
                        foreach (Form form in Application.OpenForms)
                        {
                            form.Visible = false;//隐藏已打开的所有窗口，缩小到系统托盘
                        }
                        this.hidenTheTaskBar = true;
                    }
                }
                #endregion 自启动后是否需要缩小到系统托盘      

            };
            #endregion 延迟运行一些东西

            ThemHelper.SetSystemThem();
        }


        #region 登录相关

        /// <summary>
        /// 等待登录完成
        /// </summary>
        private void LogingWait(bool isManualStart)
        {
            #region 自动登录

            if (Setting.System.AutoLoging)
            {
                LocalUserBll localUserBll = new LocalUserBll();
                string dbPath = Setting.System.DbFilePath;
                string pwd = localUserBll.GetPassword();
                if (localUserBll.Loging(dbPath, pwd).Item1 == 1)
                {
                    LoginConfirm();
                    return;//注意这里
                }
            }
            #endregion 自动登录


            #region 手动登录

            uiNavBarHeader.Enabled = false;//禁用顶部菜单栏          
            MaximizeBox = false;//隐藏放大操作按钮
            Movable = false;//设为不可拖动

            //扩展按钮
            this.ExtendMenu = null;
            this.ExtendBox = false;

            //显示登录窗口
            LogingForm logingForm = new LogingForm(this, isManualStart);
            logingForm.Show(this);

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer
            {
                Interval = 1000,
                Enabled = true//启动计时器
            };
            timer.Tick += delegate (object sender, EventArgs e)
            {
                //登录成功后操作
                if (logingForm.IsConfirm)
                {
                    timer.Stop();//停止计时器
                    logingForm.Close();
                    LoginConfirm();
                }
            };

            #endregion 手动登录
        }

        /// <summary>
        /// 登录确认后操作
        /// </summary>
        private void LoginConfirm()
        {
            #region 局域网聊天相关
            _ = Task.Factory.StartNew(() =>
            {
                try
                {
                    new ChatBll().StartChatService();//启动聊天服务             
                }
                catch (Exception ex)
                {
                    this.ShowErrorDialog(ex.Message);
                }

            }).ContinueWith(prevTask =>//任务完成后执行的回调方法（延续任务）
            {                
                ChatBll.ChatNewMessageEvent += this.ChatBll_ChatNewMessageEvent;//局域网聊天-接收到新消息事件订阅

                //同时启动聊天窗口
                if (Setting.Chat.AutoStartChatMainWindow)
                {
                    Header_MenuItemClick("局域网聊天", 0, 0);
                }                
            }, TaskScheduler.FromCurrentSynchronizationContext());//在UI主线程中运行延续任务
            #endregion 局域网聊天相关

            #region 启动需要登录才能运行的Quartz任务
            _ = Task.Factory.StartNew(() =>
            {
                try
                {                    
                    new SchedulerBll().StartJob();//启动定时任务
                    new TipsBll().StartJob();//启动事项提醒                                    
                }
                catch (Exception ex)
                {
                    this.ShowErrorDialog(ex.Message);
                }
            });
            #endregion 启动需要登录才能运行的Quartz任务

            uiNavBarHeader.Enabled = true;//启用顶部菜单栏
            MaximizeBox = true;//显示放大操作按钮
            Movable = true;//设为可拖动                  

            //扩展按钮
            this.ExtendMenu = this.uiContextMenuStripSetting;
            this.ExtendBox = true;

            StartCheckLock();//登录成功后开始检测锁屏

            FirstUse();

            ProcessMenuAction(this.args);
        }


        /// <summary>
        /// 首次运行
        /// </summary>
        private void FirstUse()
        {
            string firstUseFlagFile = Path.Combine(GlobalData.AppTempDirectory, $"{GlobalData.AppName_en}.firstuse");
            if (!File.Exists(firstUseFlagFile))//如果文件不存在则表示首次运行
            {
                AboutHelper.ShowAbout();//弹出关于窗口
                File.Create(firstUseFlagFile);
            }
        }

        #endregion 登录相关


        #region 顶部菜单

        /// <summary>
        /// 重新加载菜单
        /// </summary>
        public override void ReLoadMenus()
        {
            base.ReLoadMenus();

            LoadMenus();//加载菜单            
        }

        /// <summary>
        /// 加载功能菜单
        /// </summary>
        private void LoadMenus()
        {
            this.uiNavBarHeader.ClearAll();

            SystemMenuModel pluginsBaseMenu = SystemMenu.List.Find(it =>
            {
                return it.Text == "扩展插件";
            });
            pluginsBaseMenu.ChildMenus.Clear();

            #region 加载扩展插件菜单
            List<PluginsModel> pluginsModels = Setting.Plugins.PluginsList;

            if (pluginsModels != null && pluginsModels.Count > 0)
            {
                pluginsBaseMenu.IsShowToSysMenu = true;

                foreach (PluginsModel pluginModel in pluginsModels)
                {
                    if (!File.Exists(pluginModel.DllPath)) continue;

                    pluginsBaseMenu.ChildMenus.Add(new SystemMenuModel
                    {
                        Text = pluginModel.Text,
                        FormShowType = FormShowType.Plugins,
                        ProcessFileName = pluginModel.DllPath,
                        FormType = AssemblyHelper.GetDerivedClassesByName(pluginModel.DllPath, pluginModel.FullName),
                        PageIndex = pluginModel.Id,
                        IsShowToOperTutorial = false
                    });
                }
            }
            else
            {
                pluginsBaseMenu.IsShowToSysMenu = false;
            }
            #endregion 加载扩展插件菜单

            BindMenus(null, SystemMenu.List);

            this.uiNavBarHeader.Refresh();//刷新控件
        }


        /// <summary>
        /// 递归绑定系统菜单
        /// </summary>
        /// <param name="parentNode">父节点，为 null 时表示顶级菜单</param>
        /// <param name="systemMenuList">系统菜单列表</param>
        private void BindMenus(TreeNode parentNode, List<SystemMenuModel> systemMenuList)
        {
            // 遍历系统菜单列表
            for (int i = 0; i < systemMenuList.Count; i++)
            {
                SystemMenuModel systemMenuModel = systemMenuList[i];

                // 如果菜单不显示在系统菜单中，则跳过
                if (!systemMenuModel.IsShowToSysMenu) continue;

                // 创建并添加节点
                TreeNode node = CreateNode(parentNode, systemMenuModel, i);

                // 将菜单模型绑定到节点的 Tag 属性
                node.Tag = systemMenuModel;

                // 递归绑定子菜单
                if (systemMenuModel.ChildMenus != null && systemMenuModel.ChildMenus.Count > 0)
                {
                    BindMenus(node, systemMenuModel.ChildMenus);
                }
            }
        }

        /// <summary>
        /// 创建并添加菜单节点
        /// </summary>
        /// <param name="parentNode">父节点，为 null 时表示顶级菜单</param>
        /// <param name="systemMenuModel">系统菜单模型</param>
        /// <param name="index">节点索引</param>
        /// <returns>创建的 TreeNode 对象</returns>
        private TreeNode CreateNode(TreeNode parentNode, SystemMenuModel systemMenuModel, int index)
        {
            TreeNode node;
            if (parentNode == null)
            {
                // 创建顶级菜单节点
                node = this.uiNavBarHeader.CreateNode(systemMenuModel.Text, systemMenuModel.Symbol, systemMenuModel.SymbolSize, index);
            }
            else
            {
                // 创建子菜单节点
                node = this.uiNavBarHeader.CreateChildNode(parentNode, systemMenuModel.Text, systemMenuModel.Symbol, systemMenuModel.SymbolSize, index);
            }
            return node;
        }


        /// <summary>
        /// 顶部菜单点击事件
        /// </summary>
        /// <param name="itemText"></param>
        /// <param name="menuIndex"></param>
        /// <param name="pageIndex"></param>
        private void Header_MenuItemClick(string itemText, int menuIndex, int pageIndex)
        {
            TreeNode treeNode = TreeViewHelper.GetTreeNodeByText(this.uiNavBarHeader.Menu, itemText);

            if (treeNode == null)
            {
                this.ShowWarningNotifier("未找到相关的菜单配置");
                return;
            }

            if (!(treeNode.Tag is SystemMenuModel menuModel))
            {
                this.ShowWarningNotifier("未匹配到到相关的菜单实体");
                return;
            }

            if (menuModel.ChildMenus.Count > 0) return;

            switch (menuModel.FormShowType)
            {
                //自定义
                case FormShowType.Custom:
                    if (itemText == "锁定")
                    {
                        ShowLockForm();
                    }
                    break;
                //显示到page页
                case FormShowType.Page:
                    UIPage uIPage = (UIPage)menuModel.FormType.CreateInstance();
                    uIPage.Text = menuModel.Text;
                    TabControlHelper.AddPageToTabControl(this.uiTabControlMain, uIPage, uIPage.Text, !menuModel.AllowMultipleOpen, menuModel.PageIndex.ToString("N"));
                    break;
                //弹窗显示ShowDialog
                case FormShowType.ShowDialog:
                    UIForm uIForm = (UIForm)menuModel.FormType.CreateInstance();
                    uIForm.Text = menuModel.Text;
                    ThemHelper.SetSystemThem(uIForm);//设置主题
                    uIForm.ShowDialog(this);
                    break;
                //弹窗显示Show
                case FormShowType.Show:
                    if (menuModel.AllowMultipleOpen == false && menuModel.Form != null && menuModel.Form.IsDisposed == false)
                    {
                        menuModel.Form.HandleRunningInstance(SystemEx.SW_SHOWNOACTIVATE);//如果已经打开了，那就显示到前台
                    }
                    else
                    {
                        menuModel.Form = (UIForm)menuModel.FormType.CreateInstance();//若未打开过，那就实例化
                        menuModel.Form.Text = menuModel.Text;
                        menuModel.Form.Show();
                    }

                    break;
                //独立（外部）程序exe
                case FormShowType.ExternalEXE:
                    using (var p = Process.Start(new ProcessStartInfo
                    {
                        FileName = menuModel.ProcessFileName
                    })) { }
                    break;
                //扩展插件
                case FormShowType.Plugins:
                    if (File.Exists(menuModel.ProcessFileName))
                    {
                        PluginsForm pluginsForm = (PluginsForm)menuModel.FormType.CreateInstance();
                        pluginsForm.Text = menuModel.Text;
                        if (menuModel.AllowMultipleOpen)//允许窗口多开
                        {
                            Guid guid = Guid.NewGuid();
                            AddPage(pluginsForm, guid);
                            SelectPage(guid);
                        }
                        else//只能开一个窗口
                        {
                            if (!ExistPage(menuModel.PageIndex))
                            {
                                AddPage(pluginsForm, menuModel.PageIndex);
                            }
                            SelectPage(menuModel.PageIndex);
                        }

                        ThemHelper.SetSystemThem(pluginsForm);//设置主题
                    }
                    else
                    {
                        this.ShowWarningDialog($"未能在【{menuModel.ProcessFileName}】找到扩展插件【{menuModel.Text}】的程序集，请检查路径是否正确");
                    }
                    break;
                //未知
                default:
                    this.ShowWarningNotifier("菜单节点未维护打开方式");
                    break;
            }

            treeNode.Tag = menuModel;//重新设置下tag
        }


        #endregion


        #region TabControl相关

        /// <summary>
        /// 鼠标移过 TabPage的标签时，Tip显示截断的标题文字
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTabControlMain_MouseMove(object sender, MouseEventArgs e)
        {
            for (int i = 0; i < uiTabControlMain.TabPages.Count; i++)
            {
                //计算TabPage标签的显示区域，并检查鼠标是否在当前TabPage的标签区域内  
                if (uiTabControlMain.GetTabRect(i).Contains(new Point(e.X, e.Y)))
                {
                    if (uiTabControlMain.TabPages[i].Tag is Tuple<string, string> tagTuple)
                    {
                        uiToolTip.SetToolTip(uiTabControlMain, tagTuple.Item1);
                    }
                    break;
                }
            }
        }



        /// <summary>
        /// tabpage关闭提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        private bool uiTabControlMain_BeforeRemoveTabPage(object sender, int index)
        {
            UITabControl tabControl = sender as UITabControl;

            SystemMenuModel systemMenu = SystemMenu.GetMenuByText(tabControl.TabPages[index].Text, SystemMenu.List);

            //关闭前确认
            if (systemMenu.IsCloseConfirm)
            {
                if (new CountDownAskMessageForm($"{GlobalData.AppName_zh}-提示", $"请确认保存后再关闭窗口！", 0, UIStyle.Inherited).ShowDialog() == DialogResult.OK)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        #endregion TabControl相关


        #region 锁屏

        /// <summary>
        /// 检测锁屏
        /// </summary>
        private void StartCheckLock()
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer
            {
                Interval = 1000,
                Enabled = true
            };
            timer.Tick += delegate (object sender, EventArgs e)
            {
                if (lockState) return;

                //分钟转为秒再判断
                if (WindowsHelper.GetIdleTimeSeconds() >= (Setting.System.LockScreen_Time * 60))
                {
                    ShowLockForm();
                }
            };
        }


        /// <summary>
        /// 显示锁屏窗口
        /// </summary>
        private void ShowLockForm()
        {
            lockState = true;

            foreach (Form form in System.Windows.Forms.Application.OpenForms)
            {
                if (form.GetType() == typeof(ClockForm)) continue;//忽略：时钟窗体

                form.Visible = false;//隐藏已打开的所有窗口
            }

            //显示锁屏界面
            lockForm = new LockForm(this);
            lockForm.Show(this);

            lockForm.Visible = !hidenTheTaskBar;

            WindowsHelper.FlashWin(lockForm.Handle, 3, 1000, false);//锁屏窗口任务栏闪烁

            StartCheckUnLock();
        }


        /// <summary>
        /// 检测解锁
        /// </summary>
        private void StartCheckUnLock()
        {
            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer
            {
                Interval = 1000,
                Enabled = true
            };
            timer.Tick += delegate (object sender, EventArgs e)
            {
                if (lockForm != null && lockForm.IsConfirm)
                {
                    timer.Stop();
                    lockState = false;

                    lockForm.Dispose();//关闭锁屏窗口

                    ShowHideForm();//显示隐藏的窗口

                    WindowState = FormWindowState.Maximized;//解锁后最大化当前窗口
                    timer.Dispose();
                }
            };
        }


        /// <summary>
        /// 显示隐藏的窗口
        /// </summary>
        private void ShowHideForm()
        {
            foreach (Form form in System.Windows.Forms.Application.OpenForms)
            {
                //排除弹出的窗口，后续可以继续添加
                if (form is DataGridViewFilterForm
                    || form is ShowAttributeForm
                    || form is ChoiceMenuForm
                    || form is ComboBoxForm
                    || form is DataGridViewFilterForm
                    || form is DataSelectForm)
                {
                    continue;
                }

                form.Visible = true;//还原显示已隐藏的窗口
            }
        }

        #endregion


        #region 关闭确认

        /// <summary>
        /// 程序关闭前提示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)
            {
                // base.ExitApp();
                return;
            }
            else
            {
                int windowsclose_type = Setting.System.WindowsCloseType;

                if (windowsclose_type == 1)//缩小到系统托盘
                {
                    e.Cancel = true;

                    foreach (Form form in System.Windows.Forms.Application.OpenForms)
                    {
                        if (form.GetType() == typeof(ClockForm)) continue;//忽略：时钟窗体

                        form.Visible = false;//隐藏已打开的所有窗口
                    }
                    this.hidenTheTaskBar = true;

                    this.ShowInfoNotifier($"{GlobalData.AppName_zh}已缩小到托盘，双击图标即可打开", timeout: 2000);
                }
                else if (windowsclose_type == 2)//退出程序
                {
                    this.Hide();
                    this.notifyIcon?.Dispose();
                    base.ExitApp();
                }
                else
                {
                    this.ShowInfoNotifier("不知道要干啥");
                    e.Cancel = true;
                }
            }
        }


        #endregion


        #region 任务栏图标

        /// <summary>
        /// 双击系统右下角任务栏图标事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            RestoreWindowDisplay();
        }


        private void 显示主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            RestoreWindowDisplay();
        }


        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (this.ShowAskDialog($"{GlobalData.AppName_zh}-提示", "是否确定退出，记得保存数据！", UIStyle.Orange))
            {
                base.ExitApp();
            }
        }



        private void uiContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            this.退出ToolStripMenuItem.Visible = !lockState;//如果当前是锁屏状态，那么就不显示退出菜单
        }

        #endregion


        #region 还原窗口到前台显示

        /// <summary>
        /// 监听命名管道消息，还原窗口到前台显示
        /// </summary>
        private void ListenWindowBringToFront()
        {
            while (true)
            {
                try
                {
                    // 创建命名管道并开始监听  
                    using (NamedPipeServerStream pipeServer = new NamedPipeServerStream(GlobalData.AppName_en, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None))
                    {
                        // 等待客户端连接。 这里会阻塞线程，直到有连接才会继续往下走，所以这不是个死循环。
                        pipeServer.WaitForConnection();

                        // 读取客户端发送的消息  
                        using (StreamReader sr = new StreamReader(pipeServer))
                        {
                            string msg = sr.ReadToEnd();
                            if (msg.Contains("BringToFront"))
                            {
                                // 激活窗口到前台  
                                this.Invoke(new Action(() =>
                                {
                                    RestoreWindowDisplay();
                                }));

                                //处理右键菜单命令动作
                                if (msg.Contains("*") && msg.Contains("|"))
                                {
                                    string[] arg = msg.Split(new char[] { '*' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (arg.Length > 1)
                                    {
                                        this.args = arg[1].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                                        this.Invoke(new Action(() =>
                                        {
                                            ProcessMenuAction(this.args);
                                        }));
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
                finally
                {
                    Thread.Sleep(500);
                }
            }
        }


        /// <summary>
        /// 还原窗口显示
        /// </summary>
        private void RestoreWindowDisplay()
        {
            if (lockState)
            {
                if (lockForm == null)
                {
                    lockForm = new LockForm(this);
                }
                lockForm.Visible = true;
                lockForm.HandleRunningInstance(SystemEx.SW_NORMAL);//如果已经打开了，那就显示到前台
            }
            else
            {
                foreach (Form form in System.Windows.Forms.Application.OpenForms)
                {
                    //排除弹出的窗口，后续可以继续添加
                    if (form is DataGridViewFilterForm
                        || form is ShowAttributeForm
                        || form is ChoiceMenuForm
                        || form is ComboBoxForm
                        || form is DataGridViewFilterForm
                        || form is DataSelectForm
                        || form is ClockForm)
                    {
                        continue;
                    }

                    form.Visible = true;//显示已打开的所有窗口
                }

                this.HandleRunningInstance(SystemEx.SW_SHOWMAXIMIZED);//如果已经打开了，那就显示到前台
            }
            this.hidenTheTaskBar = false;
        }
        #endregion


        #region 窗体属性改变事件

        private void MainForm_ResizeEnd(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
            this.ShowSuccessTip($"宽：{this.Width}，高:{this.Height}", 1000, false);
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
        }

        private void MainForm_UIStyleChanged(object sender, EventArgs e)
        {
            SetBtnHelpProperty();
        }

        #endregion 窗体属性改变事件


        #region 扩展按钮菜单事件

        private void 选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OptionForm optionForm = new OptionForm())
            {
                _ = optionForm.ShowDialog();
            }
        }

        private void 主题ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Guid guid = Guid.Parse("{5AB52F69-97DF-4591-A7A3-AF846729D8B8}");
            if (!ExistPage(guid))
            {
                AddPage(new ThemeForm(), guid);
            }
            SelectPage(guid);
        }

        private void 导出数据库ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportHelper.ExportLocalDB();
        }

        private void 打开当前数据库路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.OpenDir(LocalUser.DbFilePath);
        }

        private void 打开默认数据库存放路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.OpenDir(GlobalData.LocalUserDirectory);
        }

        private void 配置文件另存为ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                FileInfo fileInfo = new FileInfo(GlobalData.IniFilePath);
                sfd.Title = $"{GlobalData.AppName_zh}配置文件另存为({fileInfo.Name})";
                sfd.Filter = $"*{fileInfo.Extension}|*{fileInfo.Extension}";
                sfd.FileName = fileInfo.Name;
                if (sfd.ShowDialog() != DialogResult.OK) return;
                fileInfo.CopyTo(sfd.FileName, true);
                this.ShowSuccessNotifier($"已另存为【{sfd.FileName}】");
            }
        }

        private void 导入配置文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Title = "请选择需要导入的配置文件";
                openFileDialog.Filter = $"{GlobalData.AppName_zh}配置文件|*.ini;";
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    if (!this.ShowAskDialog($"{GlobalData.AppName_zh}-导入提示", $"将覆盖现有的配置！{Environment.NewLine}{Environment.NewLine}导入完成后，请手动重启{GlobalData.AppName_zh}以生效。{Environment.NewLine}{Environment.NewLine}                   是否继续？", UIStyle.Orange, true, UIMessageDialogButtons.Cancel)) return;

                    File.Copy(openFileDialog.FileName, GlobalData.IniFilePath, true);
                }
            };
        }


        private void 打开配置文件路径ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.OpenDir(GlobalData.IniFilePath);
        }

        private void 打开临时目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dialogs.OpenDir(GlobalData.AppTempDirectory);
        }

        #endregion 扩展按钮菜单事件


        #region 帮助按钮

        /// <summary>
        /// 设置帮助按钮属性
        /// </summary>
        private void SetBtnHelpProperty()
        {
            this.btnHelp.BackColor = Setting.Theme.BackColor;
            this.btnHelp.RectColor = Setting.Theme.BackColor;
            this.btnHelp.Location = new Point(this.Width - 160, this.btnHelp.Location.Y);
        }


        private void btnHelp_Click(object sender, EventArgs e)
        {
            AboutHelper.ShowAbout();
        }


        private void 关于ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            AboutHelper.ShowAbout();
        }
        #endregion 帮助按钮


        #region 快捷键处理

        /// <summary>
        /// 全局快捷键监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_HotKeyEventHandler(object sender, HotKeyEventArgs e)
        {
            string hotKey = e.hotKey.ToString();

            #region 截图快捷键处理
            if (hotKey == Setting.ScreenShot.HotKey || hotKey == $"None  {Setting.ScreenShot.HotKey}")
            {
                //如果截图窗口已经打开，那就先关闭，然后重新打开
                foreach (Form form in System.Windows.Forms.Application.OpenForms)
                {
                    if (form is ScreenShotForm)
                    {
                        form.Close();
                        break;
                    }
                }
                new ScreenShotForm(true).Show();
            }
            #endregion

            #region 辅助输入快捷键处理

            else if (hotKey == Setting.AuxiliaryInput.StartHotKey || hotKey == $"None  {Setting.AuxiliaryInput.StartHotKey}")
            {
                foreach (Form form in System.Windows.Forms.Application.OpenForms)
                {
                    if (form is AuxiliaryInputForm auxiliaryInputForm)
                    {
                        auxiliaryInputForm.StartInput();
                        break;
                    }
                }
            }

            #endregion 辅助输入快捷键处理
        }

        #endregion 快捷键处理


        #region 处理右键菜单命令
        /// <summary>
        /// 处理右键菜单命令
        /// </summary>
        /// <param name="args"></param>
        private void ProcessMenuAction(string[] args)
        {
            if (args == null || args.Length <= 1) return;

            string action = StringHelper.GetCommandLineArgument(args, "Action");//命令动作参数
            string filePath = args[0];//文件路径，不是当前程序路径啊
            string extension = Path.GetExtension(filePath).ToLower();//文件扩展名

            if (string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(action)) return;

            try
            {
                BaseUIPage baseUIPage = null;

                if (action == "OpenFile")//打开文件
                {
                    //反编译程序集
                    if (extension == ".exe" || extension == ".dll" || extension == ".winmd")
                    {
                        baseUIPage = new ILSpyForm
                        {
                            Text = Path.GetFileName(filePath),
                            AssemblyPath = filePath
                        };
                    }

                    //markdown编辑器
                    else if (extension == ".md" || extension == ".markdown" || extension == ".mkdown")
                    {
                        baseUIPage = new MarkdownEditorForm2()
                        {
                            Text = Path.GetFileName(filePath),
                            FilePath = filePath,
                        };
                    }
                    //网页浏览
                    else if (extension == ".html" || extension == ".htm")
                    {
                        baseUIPage = new WebBrowserForm()
                        {
                            Text = Path.GetFileName(filePath),
                            FilePath = filePath,
                        };
                    }
                    //图片
                    else if (!string.IsNullOrEmpty(extension) && ImageHelper.GetImageFilter().Contains(extension.ToUpper()))
                    {
                        ScreenShotForm screenShotForm = new ScreenShotForm();
                        screenShotForm.Text = Path.GetFileName(filePath);
                        screenShotForm.FilePath = filePath;
                        screenShotForm.Show();
                        return;
                    }
                    //代码编辑器
                    else
                    {
                        baseUIPage = new CodeFormatForm
                        {
                            Text = Path.GetFileName(filePath),
                            FilePath = filePath
                        };
                    }
                }
                else if (action == "FolderWatcher")//监控目录
                {
                    baseUIPage = new FolderWatcherForm
                    {
                        FolderPath = filePath
                    };
                }
                else if (action == "AssemblySearch")//搜索程序集
                {
                    baseUIPage = new SearchAssemblyForm
                    {
                        FolderPath = filePath
                    };
                }
                else if (action == "BrowseImage")//浏览图片
                {
                    baseUIPage = new ImageViewForm
                    {
                        FolderPath = filePath
                    };
                }
                else if (action == "BrowseFolderSize")//查看目录大小
                {
                    baseUIPage = new FolderSizeForm
                    {
                        FolderPath = filePath
                    };
                }

                if (baseUIPage != null)
                {
                    TabControlHelper.AddPageToTabControl(this.uiTabControlMain, baseUIPage, baseUIPage.Text, true, filePath + action);
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorDialog(ex.Message);
                LogHelper.WriteErrLog(ex);
            }
        }


        #endregion 处理右键菜单命令


        /// <summary>
        /// 局域网聊天-接收到新消息事件
        /// </summary>
        /// <param name="chatRecord"></param>
        private void ChatBll_ChatNewMessageEvent(ChatRecord chatRecord)
        {
            this.BeginInvoke(new Action(() =>
            {
                //后台播放声音
                ChatBll.NotifyAudio();

                //主窗口任务栏闪烁
                WindowsHelper.FlashWin(this.Handle, 3, 1000, false);

                //右下角弹窗提醒
                ChatBll.NotifyPop($"收到{chatRecord.SendUser.IP}的消息");
            }));
        }
    }

}
